package cn.hwl.springframework.beans.factory.support;

import cn.hutool.core.bean.BeanUtil;
import cn.hwl.springframework.beans.BeansException;
import cn.hwl.springframework.beans.PropertyValue;
import cn.hwl.springframework.beans.PropertyValues;
import cn.hwl.springframework.beans.factory.config.AutowireCapableBeanFactory;
import cn.hwl.springframework.beans.factory.config.BeanDefinition;
import cn.hwl.springframework.beans.factory.config.BeanPostProcessor;
import cn.hwl.springframework.beans.factory.config.BeanReference;

import java.lang.reflect.Constructor;

/**
 * @author :  HuangWL
 * @date :    2022/4/22 19:43
 * 抽象类继承抽象类不需要强制实现 所有抽象方法；普通类则需要
 *  实现创建bean方法：实现了 Bean 的实例化操作 newInstance，
 *  实现完成后直接调用 addSingleton 方法存放到单例对象的缓存中
 */
public  abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFactory implements AutowireCapableBeanFactory {

    private InstantiationStrategy instantiationStrategy = new CglibSubclassingInstantiationStrategy();

    @Override
    protected Object createBean(String beanName, BeanDefinition beanDefinition, Object[] args) throws BeansException {

        Object bean;
        try {
            bean = createBeanInstance(beanDefinition,beanName,args);
            //给 Bean 填充属性
            applyPropertyValues(beanName, bean, beanDefinition);
            // 执行 Bean 的初始化方法和 BeanPostProcessor 的前置和后置处理方法
            bean = initializeBean(beanName, bean, beanDefinition);
        }catch (Exception e){
            throw new BeansException("Instantiation of bean failed",e);
        }

        addSingleton(beanName, bean);
        return bean;
    }

    private Object initializeBean(String beanName, Object bean, BeanDefinition beanDefinition) {
        // 1. 执行 BeanPostProcessor Before 处理
        Object wrappedBean = applyBeanPostProcessorsBeforeInitialization(bean, beanName);

        // 待完成内容：invokeInitMethods(beanName, wrappedBean, beanDefinition);
        invokeInitMethods(beanName, wrappedBean, beanDefinition);

        // 2. 执行 BeanPostProcessor After 处理
        wrappedBean = applyBeanPostProcessorsAfterInitialization(bean, beanName);
        return wrappedBean;
    }

    private void invokeInitMethods(String beanName, Object wrappedBean, BeanDefinition beanDefinition) {

    }

    @Override
    public Object applyBeanPostProcessorsBeforeInitialization(Object existingBean, String beanName) throws BeansException {
        Object result = existingBean;
        for (BeanPostProcessor processor : getBeanPostProcessors()) {
            Object current = processor.postProcessBeforeInitialization(result, beanName);
            if (null == current) return result;
            result = current;
        }
        return result;
    }
    @Override
    public Object applyBeanPostProcessorsAfterInitialization(Object existingBean, String beanName) throws BeansException {
        Object result = existingBean;
        for (BeanPostProcessor processor : getBeanPostProcessors()) {
            Object current = processor.postProcessAfterInitialization(result, beanName);
            if (null == current) return result;
            result = current;
        }
        return result;
    }

    //04章：抽取createBeanInstance 方法
    protected Object createBeanInstance(BeanDefinition beanDefinition,String beanName,Object[] args){
        Constructor constructorToUse = null;
        Class<?> beanClass = beanDefinition.getBeanClass();
        //获取全部构造参数
        Constructor<?>[] declaredConstructors  = beanClass.getConstructors();
        for (Constructor ctor : declaredConstructors) {
            //遍历所有构造函数，构造函数参数长度与入参长度一致时，取出（实际的spring还有类型比对）
            if ( args != null && ctor.getParameterTypes().length == args.length){
                constructorToUse = ctor;
            }
            break;
        }
        return getInstantiationStrategy().instantiate(beanDefinition, beanName, constructorToUse, args);
    }

    //属性填充
    protected void applyPropertyValues(String beanName,Object bean,BeanDefinition beanDefinition){
        try {
            PropertyValues propertyValues = beanDefinition.getPropertyValues();
            for (PropertyValue propertyValue : propertyValues.getPropertyValues()) {

                String name = propertyValue.getName();
                Object value = propertyValue.getValue();

                if (value instanceof BeanReference) {
                    // A 依赖 B，获取 B 的实例化：a填充属性时，发现类中有属性为b，去尝试加载b，递归生成B的实例。
                    //BeanFactory 在map中注入两组 BeanDefinition（），其中一组的BeanDefinition 装入一组 PropertyValues
                    //PropertyValues 中有一组propertyValue 的value 是BeanReference类型。
                    //本方法取到该 BeanReference，通过BeanReference存入的 beanName去获取实例 bean，赋值给原value
                    // 讲value值 填充给 入参bean
                    BeanReference beanReference = (BeanReference) value;
                    String referenceBeanName = beanReference.getBeanName();
                    value = getBean(referenceBeanName);
                }
                // 属性填充
                BeanUtil.setFieldValue(bean, name, value);
            }
        } catch (Exception e) {
            throw new BeansException("Error setting property values：" + beanName);
        }
    }





    public InstantiationStrategy getInstantiationStrategy(){
        return instantiationStrategy;
    }
    public void setInstantiationStrategy(InstantiationStrategy instantiationStrategy) {
        this.instantiationStrategy = instantiationStrategy;
    }
}
